"""
监控API处理器
提供模型监控和性能数据的REST API接口
"""

from flask import Blueprint, jsonify, request
from api.utils.model_monitor import model_monitor
from api.utils.auto_learning import AutoLearningManager
from datetime import datetime
import logging

monitor_bp = Blueprint('monitor', __name__)
logger = logging.getLogger(__name__)

@monitor_bp.route('/dashboard', methods=['GET'])
def get_dashboard():
    """获取实时仪表板数据"""
    try:
        dashboard_data = model_monitor.get_real_time_dashboard()
        return jsonify({
            'status': 'success',
            'data': dashboard_data
        })
    except Exception as e:
        logger.error(f"获取仪表板数据失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@monitor_bp.route('/metrics', methods=['GET'])
def get_metrics():
    """获取性能指标数据"""
    try:
        limit = request.args.get('limit', 100, type=int)
        summary = model_monitor.get_performance_summary()
        
        return jsonify({
            'status': 'success',
            'data': summary,
            'limit': limit
        })
    except Exception as e:
        logger.error(f"获取性能指标失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@monitor_bp.route('/metrics/export', methods=['POST'])
def export_metrics():
    """导出性能指标数据"""
    try:
        data = request.get_json() or {}
        filename = data.get('filename')
        
        exported_file = model_monitor.export_metrics(filename)
        
        return jsonify({
            'status': 'success',
            'message': f'指标数据已导出到 {exported_file}',
            'filename': exported_file
        })
    except Exception as e:
        logger.error(f"导出指标数据失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@monitor_bp.route('/learning/status', methods=['GET'])
def get_learning_status():
    """获取自动学习状态"""
    try:
        auto_learner = AutoLearningManager()
        status = auto_learner.get_learning_status()
        
        return jsonify({
            'status': 'success',
            'data': status
        })
    except Exception as e:
        logger.error(f"获取学习状态失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@monitor_bp.route('/learning/trigger', methods=['POST'])
def trigger_learning():
    """手动触发自动学习"""
    try:
        auto_learner = AutoLearningManager()
        result = auto_learner.trigger_training()
        
        return jsonify({
            'status': 'success',
            'message': '自动学习已触发',
            'data': result
        })
    except Exception as e:
        logger.error(f"触发自动学习失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@monitor_bp.route('/learning/feedback', methods=['POST'])
def submit_feedback():
    """提交用户反馈"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                'status': 'error',
                'message': '请求数据不能为空'
            }), 400
        
        required_fields = ['question', 'answer', 'user_feedback', 'score']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'status': 'error',
                    'message': f'缺少必要字段: {field}'
                }), 400
        
        auto_learner = AutoLearningManager()
        result = auto_learner.add_feedback(
            question=data['question'],
            answer=data['answer'],
            user_feedback=data['user_feedback'],
            score=data['score'],
            correct_answer=data.get('correct_answer')
        )
        
        return jsonify({
            'status': 'success',
            'message': '反馈已提交',
            'data': result
        })
    except Exception as e:
        logger.error(f"提交反馈失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@monitor_bp.route('/learning/feedback/stats', methods=['GET'])
def get_feedback_stats():
    """获取反馈统计信息"""
    try:
        auto_learner = AutoLearningManager()
        stats = auto_learner.get_feedback_statistics()
        
        return jsonify({
            'status': 'success',
            'data': stats
        })
    except Exception as e:
        logger.error(f"获取反馈统计失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@monitor_bp.route('/health/detailed', methods=['GET'])
def get_detailed_health():
    """获取详细健康检查"""
    try:
        from api.services.neo4j_service import neo4j_service
        
        # 数据库状态
        db_status = neo4j_service.check_database_status()
        
        # 监控状态
        monitor_status = model_monitor.get_real_time_dashboard()
        
        # 学习状态
        auto_learner = AutoLearningManager()
        learning_status = auto_learner.get_learning_status()
        
        health_data = {
            'database': db_status,
            'monitoring': monitor_status,
            'learning': learning_status,
            'timestamp': datetime.now().isoformat()
        }
        
        return jsonify({
            'status': 'success',
            'data': health_data
        })
    except Exception as e:
        logger.error(f"获取健康检查失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@monitor_bp.route('/config', methods=['GET'])
def get_monitor_config():
    """获取监控配置"""
    try:
        config = model_monitor.config
        return jsonify({
            'status': 'success',
            'data': config
        })
    except Exception as e:
        logger.error(f"获取监控配置失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@monitor_bp.route('/config', methods=['PUT'])
def update_monitor_config():
    """更新监控配置"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                'status': 'error',
                'message': '请求数据不能为空'
            }), 400
        
        # 这里应该实现配置更新逻辑
        # 简化处理，实际应该保存到配置文件
        
        return jsonify({
            'status': 'success',
            'message': '监控配置已更新'
        })
    except Exception as e:
        logger.error(f"更新监控配置失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

# 错误处理
@monitor_bp.errorhandler(404)
def not_found(error):
    return jsonify({
        'status': 'error',
        'message': 'API端点不存在'
    }), 404

@monitor_bp.errorhandler(500)
def internal_error(error):
    return jsonify({
        'status': 'error',
        'message': '服务器内部错误'
    }), 500